package com.yunxun.coinmessage.controller;

import com.google.gson.Gson;
import com.yunxun.coinmessage.entity.*;
import com.yunxun.coinmessage.model.JsonBean;
import com.yunxun.coinmessage.model.SingleJsonBean;
import com.yunxun.coinmessage.templatedata.CoinTemplateData;
import com.yunxun.coinmessage.templatedata.ContentConditionTemplateData;
import com.yunxun.coinmessage.templatedata.ContentTamplateData;
import com.yunxun.coinmessage.templatedata.MsgResult;
import com.yunxun.coinmessage.service.*;
import com.yunxun.coinmessage.sqlvo.ContentVO;
import okhttp3.*;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;

@Controller
public class ContentController {
    @Autowired
    ContentService contentService;
    @Autowired
    CoinService coinService;
    @Autowired
    ExchangeService exchangeService;
    @Autowired
    ProgramService programService;
    @Value("${content.ip}")
    private String contentIp;
    /**
     * 打开新增内容的窗口并回显币种和交易所
     * @param model
     * @return
     */
   @RequestMapping("/openContentAdd")
    public String openContentAdd( Model model){

        List<Coin> coinList=coinService.queryAll();
        List<Exchange> exchangeList=exchangeService.queryAll();
        List<Program> programList=programService.queryAll();
        List<CoinTemplateData> coinTemplateDataList=new ArrayList<>();
        for(Coin coin:coinList){
            CoinTemplateData coinTemplateData=new CoinTemplateData();
            coinTemplateData.setSelectCoin("("+coin.getCcode().toLowerCase()+")"+coin.getCname());
            coinTemplateData.setCid(coin.getCid());
            coinTemplateDataList.add(coinTemplateData);
        }
        model.addAttribute("coinTemplateDataList",coinTemplateDataList);
        model.addAttribute("exchangeList",exchangeList);
        model.addAttribute("programList",programList);
        return  "content-add";
    }
    @RequestMapping("/addContent")
    @ResponseBody
    public ModelAndView addContent(@org.springframework.web.bind.annotation.RequestBody @Valid Content content,BindingResult result)throws Exception{
       if(result.hasErrors()){
           throw new Exception(result.getFieldError().getDefaultMessage());
       }
       SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       Date date=simpleDateFormat.parse(content.getFormat_time());
       long l=date.getTime();
       content.setCreate_time(l/1000);
       contentService.addContent(content);
       return new ModelAndView("redirect:/queryContentByPage?start = 0&limit = 10");
    }

    //给采集内容使用的接口
    @RequestMapping("/addContentByCollector")
    @ResponseBody
    public MsgResult addContentByCollector(@org.springframework.web.bind.annotation.RequestBody @Valid HttpServletRequest request, Content content, BindingResult result){
       if(result.hasErrors()){
           return new MsgResult(false,result.getFieldError().getDefaultMessage());
       }
       String ua = request.getHeader("user-agent");
       if (Strings.isEmpty(ua)) {
           return new MsgResult(false,"错误");
       }
       if (!"crawler".equals(ua)) {
           return new MsgResult(false,"错误");
       }
       if(content.getCreate_time() == null ||content.getCreate_time()==0){
           content.setCreate_time(System.currentTimeMillis()/1000);
       }
      MsgResult msgResult=  contentService.addContentByCollector(content);
       return msgResult;
    }



    @RequestMapping("/queryContentByPage")
    public String queryContentByPage(ContentVO contentVO,Model model){
       List<ContentTamplateData> contentTamplateDataList =contentService.queryByPage(contentVO);
       Integer total=contentService.queryTotal();
       Integer totalPage=(total+19)/20;
       ContentConditionTemplateData contentConditionTemplateData =contentService.getContentConditionModel();
       model.addAttribute("contentConditionTemplateData", contentConditionTemplateData);
       model.addAttribute("total",total);
       model.addAttribute("totalPage",totalPage);
       return "content-list";
    }
    @RequestMapping("/queryContentByPage1")
    @ResponseBody
    public List<ContentTamplateData> queryContentByPage1(ContentVO contentVO){
        List<ContentTamplateData> contentTamplateDataList =contentService.queryByPage(contentVO);
        return contentTamplateDataList;
    }

    /**
     * 该方法存在仅仅是为了得到组合条件查询的总记录数和分页数和条件下拉选内容
     * @param contentVO
     * @param model
     * @return
     */
    @RequestMapping("/queryContentByCondition")
    public String queryByCondition(ContentVO contentVO,Model model){
        int total=contentService.queryTotalByCondition(contentVO);
        int totalPage=(total+19)/20;
        ContentConditionTemplateData contentConditionTemplateData =contentService.getContentConditionModel();
        model.addAttribute("contentConditionTemplateData", contentConditionTemplateData);
        model.addAttribute("total",total);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("contentVO",contentVO);
        return "content-list";
    }



    @RequestMapping("/queryContentById")
    public String queryContenById(Integer con_id,Model model) throws Exception{
       if(contentService.queryContentById(con_id)==null){
           throw new Exception("要查看的内容不存在");
       }
       Content content= contentService.queryContentById(con_id);
       //将标题中含html标签"<"和">"进行转义
        String con_title=content.getCon_title().replaceAll("<","&lt");
        con_title=con_title.replaceAll(">","&gt");
        content.setCon_title(con_title);
       model.addAttribute("content",content);
       return "content";
    }


    /**
     * 打开编辑内容的窗口,并回显数据
     * @param con_id
     * @param model
     * @return
     */
    @RequestMapping("/openEditContentWindow")
    public String openEditContentWindow(Integer con_id,Model model)throws Exception{
        if(con_id==null ){
            throw new Exception("发生错误");
        }
        Content content=contentService.queryContentById(con_id);
        List<Exchange> exchangeList=exchangeService.queryAll();
        List<Coin> coinList=coinService.queryAll();
        List<Program> programList=programService.queryAll();
        model.addAttribute("coinList",coinList);
        model.addAttribute("exchangeList",exchangeList);
        model.addAttribute("programList",programList);
        model.addAttribute("content",content);
        //格式化时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time=content.getCreate_time()*1000;
        Date date=new Date(time);
        content.setFormat_time(simpleDateFormat.format(date));
        return "content-edit";
    }
    @RequestMapping("/editContentById")
    @ResponseBody
    public MsgResult editContentById(Content content) throws Exception{
        //判断要修改的program是否存在
        if(programService.queryById(content.getProgram_id())==null){
            throw new Exception("你要修改的栏目不存在");
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=simpleDateFormat.parse(content.getFormat_time());
        long l=date.getTime();
        content.setCreate_time(l/1000);
       return contentService.updateContentById(content);
    }

    /**
     * 打开审核的窗口，并从咨询服务器获得总记录数
     * @param model
     * @return
     */
    @RequestMapping("/openCheckContent")
    public String openCheckContent(ContentVO contentVO,Model model) throws Exception {
            contentVO.setStart(1);
            contentVO.setLimit(20);
            JsonBean jsonBean=requestContenServer(contentVO);
            if(jsonBean==null){
                throw new Exception("jsonBean为null");
            }
            int total=jsonBean.getResult().getTotal();
            model.addAttribute("total",total);
            model.addAttribute("contentVo",contentVO);
            ContentConditionTemplateData contentConditionTemplateData =contentService.getContentConditionModel();
            model.addAttribute("contentConditionTemplateData", contentConditionTemplateData);
            int totalPage=(total+19)/20;
            model.addAttribute("totalPage",totalPage);
            return "content-check-list";
    }

    /**
     * 分页请求审核资讯内容
     * @param contentVO
     * @return
     */
    @RequestMapping("/checkContent")
    @ResponseBody
    public JsonBean checkContent(ContentVO contentVO){
       try{
           return requestContenServer(contentVO);
       }
       catch (Exception e){
           e.printStackTrace();
       }
       return null;
    }

    /**
     * 查询文章服务器指定id的文章
     * @param contentVO
     * @param model
     * @return
     */
    @RequestMapping("/queryArticle")
    public String queryArticle(ContentVO contentVO,Model model){
        Content content=conversionSingleJsonBean(contentVO);
        model.addAttribute("content",content);
        return "content-receive";
    }

    /**
     * 审核通过插入数据库，并调用接口告诉获得资讯内容的服务器文章状态（已发布，不符合发布）
     * @param content
     * @return
     * @throws IOException
     */
    @RequestMapping("/isPassContent")
    @ResponseBody
    public MsgResult isPassContent(Content content) throws IOException {
        MsgResult msgResult=new MsgResult(true,"不符合发布");//当status=0时msgResult的默认值
        if(content.getStatus()!=0){
             msgResult=contentService.addContentByCollector(content);
        }
        //调用接口告诉获得资讯内容的服务器的文章状态
        if(msgResult.getStatus()){
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            String timestamp = String.valueOf(System.currentTimeMillis());
            String nonce="123456";
            String url=contentIp+"/api/archives/status?id="+content.getId()+"&status="+content.getStatus();
            String sig = DigestUtils.md5Hex(String.format("%s-%s-ss20180421", nonce, timestamp));
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("content-type", "application/json")
                    .addHeader("timestamp", timestamp)
                    .addHeader("nonce", nonce)
                    .addHeader("sig", sig)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("postman-token", "edaac2bb-4842-bb90-afaf-584772da8ef2")
                    .build();
            Response response = client.newCall(request).execute();
        }
        return msgResult;
    }

    /**
     * 打开审核的窗口并回显
     * @param contentVO
     * @param model
     * @return
     */
    @RequestMapping ("/openCheckWindow")
    public String openCheckWindow(ContentVO contentVO,Model model){
        try {
            Content content=conversionSingleJsonBean(contentVO);
            List<Exchange> exchangeList=exchangeService.queryAll();
            List<Coin> coinList=coinService.queryAll();
            List<Program> programList=programService.queryAll();
            List<CoinTemplateData> coinTemplateDataList=new ArrayList<>();
            for(Coin coin:coinList){
                CoinTemplateData coinTemplateData=new CoinTemplateData();
                coinTemplateData.setSelectCoin("("+coin.getCcode().toLowerCase()+")"+coin.getCname());
                coinTemplateData.setCid(coin.getCid());
                coinTemplateDataList.add(coinTemplateData);
            }
            model.addAttribute("coinList",coinList);
            model.addAttribute("exchangeList",exchangeList);
            model.addAttribute("coinTemplateDataList",coinTemplateDataList);
            model.addAttribute("programList",programList);
            model.addAttribute("content",content);
            model.addAttribute("id",contentVO.getId());
            return "content-check";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    @RequestMapping("/updateContentStatusById")
    @ResponseBody
    public MsgResult updateStatus(Integer con_id, Integer status)throws Exception{
        if(contentService.queryContentById(con_id)==null){
            throw new Exception("你要修改的资讯不存在");
        }
        return contentService.updateStatus(con_id,status);
    }


    /**
     * 请求内容服务器，并将栏目id,模型id 转换为栏目名称，模型名称和格式化哈时间戳
     * @param contentVO
     * @return
     * @throws Exception
     */
    public JsonBean requestContenServer(ContentVO contentVO) throws Exception {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        String s="{column:"+contentVO.getProgram_id()+",exchange:"+contentVO.getExchange_id()+",digitalCash:"+contentVO.getCoin_id()+",page:"+contentVO.getStart()+",pageSize:"+contentVO.getLimit()+"}";
        RequestBody body = RequestBody.create(mediaType, s);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = "123456";
        String sig = DigestUtils.md5Hex(String.format("%s-%s-ss20180421", nonce, timestamp));
        String url=contentIp+"/api/archives/search";
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("timestamp", timestamp)
                .addHeader("nonce", "123456")
                .addHeader("sig", sig)
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "edaac2bb-4842-bb90-afaf-584772da8ef2")
                .build();
        try {
            Response response = client.newCall(request).execute();
//            JSONObject jsonObject= new JSONObject( response.body().string());
//            JSONObject jsonObject1=new JSONObject(jsonObject.getString("result"));
            Gson gson = new Gson();
            JsonBean jsonBean= gson.fromJson(response.body().string(),JsonBean.class);
            //格式化时间戳
            SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //遍历result中的list集合并转换为标准格式的时间
            List<JsonBean.Result.ReceiveContent> receiveContents=jsonBean.getResult().getList();
            for(JsonBean.Result.ReceiveContent receiveContent:jsonBean.getResult().getList()){
                //格式化时间
                Long time=receiveContent.getCreate_time()*1000;
                Date date=new Date(time);
                String formatTime=format.format(date);
                receiveContent.setFormatTime(formatTime);
                //将"<"和">"转换成&lt和&gt
               String title= receiveContent.getTitle();
               title=title.replaceAll("<","&lt");
               title=title.replaceAll(">","&gt");
               receiveContent.setTitle(title);
                //将栏目id,模型id 转换为栏目名称
                if(receiveContent.getColumn()==1){
                    Program program=programService.queryById(receiveContent.getColumn());
                    if(program==null){
                        throw new Exception("无法找到该栏目");
                    }
                    receiveContent.setProgram_name(program.getProgram_name());
                    if( receiveContent.getDigital_cash()!=0){
                        Coin coin= coinService.queryById(receiveContent.getDigital_cash());
                        if(coin==null){
                            throw new Exception("无法找到该币种");
                        }
                        receiveContent.setCname(coin.getCname());
                    }
                }else if(receiveContent.getColumn()==2){
                    Program program=programService.queryById(receiveContent.getColumn());
                    if(program==null){
                        throw new Exception("无法找到该栏目");
                    }
                    receiveContent.setProgram_name(program.getProgram_name());
                    if( receiveContent.getDigital_cash()!=0){
                       Coin coin= coinService.queryById(receiveContent.getDigital_cash());
                       if(coin==null){
                           throw new Exception("无法找到该币种");
                       }
                        receiveContent.setCname(coin.getCname());
                    }
                }else {//交易所公告
                    Program program=programService.queryById(receiveContent.getColumn());
                    if(program==null){
                        throw new Exception("无法找到该栏目");
                    }
                    receiveContent.setProgram_name(program.getProgram_name());
                    if(receiveContent.getExchange()!=0){
                        Exchange exchange=exchangeService.queryById(receiveContent.getExchange());
                        if(exchange==null){
                            throw new Exception("无法找到该交易所");
                        }
                        receiveContent.setEname(exchange.getEname());
                    }
                }
            }
            return jsonBean;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Content conversionSingleJsonBean(ContentVO contentVO){
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
//        String s="{column:"+contentVO.getProgram_id()+",exchange:"+contentVO.getExchange_id()+",digitalCash:"+contentVO.getCoin_id()+",page:"+contentVO.getStart()+",pageSize:"+contentVO.getLimit()+"}";
//        RequestBody body = RequestBody.create(mediaType, s);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = "123456";
        String sig = DigestUtils.md5Hex(String.format("%s-%s-ss20180421", nonce, timestamp));
        Request request = new Request.Builder()
                .url("http://122.228.226.38:10899/api/archives/doc?id="+contentVO.getId())
                .get()
                .addHeader("content-type", "application/json")
                .addHeader("timestamp", timestamp)
                .addHeader("nonce", "123456")
                .addHeader("sig", sig)
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "edaac2bb-4842-bb90-afaf-584772da8ef2")
                .build();
        try {
            Response response = client.newCall(request).execute();
            Gson gson = new Gson();
            SingleJsonBean singleJsonBean= gson.fromJson(response.body().string(),SingleJsonBean.class);
            Content content=new Content();
            content.setProgram_id(singleJsonBean.getResult().getColumn());
            content.setExchange_id(singleJsonBean.getResult().getExchange());
            content.setCoin_id(singleJsonBean.getResult().getDigital_cash());
            content.setCon_author(singleJsonBean.getResult().getSource_name());
            content.setCon_addr(singleJsonBean.getResult().getSource_link());
            content.setVerifycode(singleJsonBean.getResult().getHash_code());
            content.setCreate_time(singleJsonBean.getResult().getCreate_time());
            content.setId(singleJsonBean.getResult().getId());
            //对获得指定文章标题中含有html标签"<"和">"进行转义
            String con_title=singleJsonBean.getResult().getTitle().replaceAll("<","&lt");
            con_title=con_title.replaceAll(">","&gt");
            content.setCon_title(con_title);

            //处理文章内容,如果有原文标题的情况
            StringBuilder con_article=new StringBuilder();
            if(singleJsonBean.getResult().getOther().getSource_title()!=null ){
                con_article.append("<h3 class=\"orging\"><span class=\"translator\">【Google翻译】</span>");
                con_article.append(singleJsonBean.getResult().getContent());
                if(singleJsonBean.getResult().getOther().getSource_content()!=null){
                    con_article.append("</h3> <blockquote class=\"orging-content\" style=\"background: rgb(246, 246, 246); padding: 8px; margin: 0px;\"><h4>");
                    con_article.append("原文标题:");
                    con_article.append(singleJsonBean.getResult().getOther().getSource_title());
                    con_article.append("</h4><p>");
                    con_article.append("原文:");
                    con_article.append(singleJsonBean.getResult().getOther().getSource_content());
                    con_article.append("</p></blockquote>");
                }
            }else {//没有原文标题的情况

                con_article.append("<h3 class=\"orging\">");
                if (singleJsonBean.getResult().getOther().getSource_content() != null) {
                    con_article.append("<span class=\"translator\">【Google翻译】</span>");
                }
                con_article.append(singleJsonBean.getResult().getContent());
                if (singleJsonBean.getResult().getOther().getSource_content() != null) {
                    con_article.append("</h3> <blockquote class=\"orging-content\" style=\"background: rgb(246, 246, 246); padding: 8px; margin: 0px;\">");
                    con_article.append("原文:");
                    con_article.append("<p>");
                    con_article.append(singleJsonBean.getResult().getOther().getSource_content());
                    con_article.append("</p></blockquote>");
                }
            }
            content.setCon_article(con_article.toString());
            return content;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

